// public/client.js
const ws = new WebSocket(`ws://${location.host}`);
const usernameInput = document.getElementById('username');
const messagesUl = document.getElementById('messages');
const onlineSpan = document.getElementById('onlineList');
const form = document.getElementById('form');
const input = document.getElementById('input');

let username = '';

// 昵称回车确认
usernameInput.addEventListener('keydown', (e) => {
  if (e.key === 'Enter' && usernameInput.value.trim()) {
    username = usernameInput.value.trim();
    usernameInput.disabled = true;
    ws.send(JSON.stringify({ type: 'login', payload: username }));
  }
});

// 渲染消息
function appendMsg({ from, content, private: isPrivate }) {
  const li = document.createElement('li');
  li.className = 'mb-1';
  li.innerHTML = `<span class="font-semibold ${isPrivate ? 'text-purple-600' : ''}">
    ${from}${isPrivate ? '（私聊）' : ''}:
  </span> ${content}`;
  messagesUl.appendChild(li);
  messagesUl.scrollTop = messagesUl.scrollHeight;
}

// 处理后端推送
ws.onmessage = ({ data }) => {
  const { type, payload } = JSON.parse(data);

  if (type === 'history') {
    payload.forEach(appendMsg);
  } else if (type === 'chat') {
    appendMsg(payload);
  } else if (type === 'onlineList') {
    onlineSpan.textContent = payload.join(', ');
  }
};

// 发送消息
form.addEventListener('submit', (e) => {
  e.preventDefault();
  if (!username) {
    alert('先输入昵称！');
    return;
  }
  if (!input.value.trim()) return;

  ws.send(JSON.stringify({ type: 'chat', payload: { text: input.value.trim() } }));
  input.value = '';
});